import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Form, Input, message } from 'antd'
import ArbitratorSelector from '../ArbitratorSelector/Index'
import { Line, Cell, Split } from '@components/ApprovePre/Approve'
import Text from '@components/Text'
import { defaultProcedure } from '@src/assets/js/config'

const { Item } = Form

export default class SecretaryGeneralInput extends Component {
  state = {
    asVisible: false,
    currentForm: null,
    currentArbitratorObj: {},
    currentArbitratorPath: [],
    currentArbitratoridPath: [],
    currentAction: null,
    actionMap: {},
    disabledIdList: []
  }

  // 设置编辑中的仲裁员
  setModifyArbitrator (form, arbpath, arbidpath) {
    const name = form.current.getFieldValue(arbpath)
    const id = form.current.getFieldValue(arbidpath)
    this.setState({
      asVisible: true,
      currentArbitratorObj: { arbitrator: name || '', arbitratorid: id || '' },
      currentForm: form,
      currentArbitratorPath: arbpath,
      currentArbitratoridPath: arbidpath
    })
  }

  // 限制重复选择仲裁员
  isHasSameSelected (arbitratorid, arbitrator) {
    const keyType = this.state.currentArbitratoridPath[0]
    const formRef = this.state.currentForm.current
    const id = formRef.getFieldValue(['arbitratorid'])
    const id1 = formRef.getFieldValue(['arbitratorid1'])
    const id2 = formRef.getFieldValue(['arbitratorid2'])
    if ((keyType === 'arbitratorid' && [id1, id2].indexOf(arbitratorid) !== -1) || (keyType === 'arbitratorid1' && [id, id2].indexOf(arbitratorid) !== -1) || (keyType === 'arbitratorid2' && [id, id1].indexOf(arbitratorid) !== -1)) {
      message.warning(`仲裁员 ${arbitrator} 已被选择`)
      return true
    }
    return false
  }

  // 改变仲裁员选择器
  onChangeArbitrator ({ arbitratorid, arbitrator }) {
    const isNormal = this.props.caseDetail.procedure === defaultProcedure
    if (isNormal && arbitratorid && this.isHasSameSelected(arbitratorid, arbitrator)) {
      return false
    }
    const arbPath = this.state.currentArbitratorPath
    const arbidPath = this.state.currentArbitratoridPath
    const current = this.state.currentForm.current
    const nP = { [arbPath[0]]: current.getFieldValue(arbPath[0]) }
    const iP = { [arbidPath[0]]: current.getFieldValue(arbidPath[0]) }
    let name = nP[arbPath[0]]
    let id = iP[arbidPath[0]]
    for (let i = 1; i < arbPath.length - 1; i++) {
      name = name[arbPath[i]]
    }
    if (arbPath.length > 1) {
      name[arbPath[arbPath.length - 1]] = arbitrator
    } else {
      nP[arbPath[0]] = arbitrator
    }
    for (let i = 1; i < arbidPath.length - 1; i++) {
      id = id[arbidPath[i]]
    }
    if (arbidPath.length > 1) {
      id[arbidPath[arbidPath.length - 1]] = arbitratorid
    } else {
      iP[arbidPath[0]] = arbitratorid
    }
    current.setFieldsValue({
      ...nP,
      ...iP
    })
    this.setState({
      currentArbitratorPath: [],
      currentArbitratoridPath: [],
      currentArbitratorObj: {},
      currentForm: null
    })
  }

  // 获取初始化数据
  getInitData () {
    const court = this.props.instance.formCourt
    const data = {
      arbitrator: court.arbitrator_recommend,
      arbitratorid: court.arbitratorid_recommend,
      arbitrator1: court.arbitrator1_recommend,
      arbitratorid1: court.arbitratorid1_recommend,
      arbitrator2: court.arbitrator2_recommend,
      arbitratorid2: court.arbitratorid2_recommend
    }
    if (court.arbitratorid_claimant === court.arbitratorid_respondent && court.arbitratorid_claimant) {
      data.arbitrator_recommend = court.arbitrator_claimant
      data.arbitratorid_recommend = court.arbitratorid_claimant
    }
    if (court.arbitratorid1_claimant && court.arbitratorid1_claimant !== court.arbitratorid1_respondent) {
      data.arbitrator1_recommend = court.arbitrator1_claimant
      data.arbitratorid1_recommend = court.arbitratorid1_claimant
    }
    if (court.arbitratorid1_respondent && court.arbitratorid1_respondent !== court.arbitratorid1_claimant) {
      data.arbitrator2_recommend = court.arbitrator1_respondent
      data.arbitratorid2_recommend = court.arbitratorid1_respondent
    }
    return data
  }

  // 设置首席仲裁员禁用id
  setPrimaryDiabledId () {
    const court = this.props.instance.formCourt
    const s = new Set()
    court.tribunal_party.forEach(li => {
      s.add(li.arbitratorid)
    })
    const ids = [...s]
    if (ids.length > 1) {
      this.setState({
        disabledIdList: ids.filter(i => i)
      })
    }
  }

  renderNormal (data) {
    if (this.props.caseDetail.procedure === defaultProcedure) {
      return (
        <>
          <Split />
          <Cell>
            <Item noStyle name='arbitratorid1'><span /></Item>
            <Item label='仲裁员' name='arbitrator1' rules={[{ required: true, message: '仲裁员不能为空' }]}>
              {
                data.arbitratorid1_recommend ? (
                  <Text format={v => `${v}（共同选定）`} />
                ) : (
                  <Input
                    placeholder='请选择仲裁员' readOnly onClick={() => {
                      if (data.arbitratorid1_recommend) {
                        return false
                      }
                      this.setModifyArbitrator(this.props.formRef, ['arbitrator1'], ['arbitratorid1'])
                    }}
                  />
                )
              }
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item noStyle name='arbitratorid2'><span /></Item>
            <Item label='仲裁员' name='arbitrator2' rules={[{ required: true, message: '仲裁员不能为空' }]}>
              {
                data.arbitratorid2_recommend ? (
                  <Text format={v => `${v}（共同选定）`} />
                ) : (
                  <Input
                    placeholder='请选择仲裁员' readOnly onClick={() => {
                      if (data.arbitratorid2_recommend) {
                        return false
                      }
                      this.setModifyArbitrator(this.props.formRef, ['arbitrator2'], ['arbitratorid2'])
                    }}
                  />
                )
              }
            </Item>
          </Cell>
        </>
      )
    }
  }

  render () {
    const data = this.getInitData()
    const isNormal = this.props.caseDetail.procedure === defaultProcedure
    return (
      <div>
        <ArbitratorSelector value={this.state.currentArbitratorObj} visible={this.state.asVisible} caseDetail={this.props.caseDetail} hide={() => this.setState({ asVisible: false, disabledIdList: [] })} onChange={o => this.onChangeArbitrator(o)} disabledIdList={this.state.disabledIdList} />
        <Line>
          <Cell>
            <Item noStyle name='arbitratorid'><span /></Item>
            <Item label={isNormal ? '首席仲裁员' : '仲裁员'} name='arbitrator' rules={[{ required: true, message: '首席仲裁员不能为空' }]}>
              {
                data.arbitratorid_recommend ? (
                  <Text format={v => `${v}（共同选定）`} />
                ) : (
                  <Input
                    placeholder='请选择仲裁员' readOnly onClick={() => {
                      if (data.arbitratorid_recommend) {
                        return false
                      }
                      this.setPrimaryDiabledId()
                      this.setModifyArbitrator(this.props.formRef, ['arbitrator'], ['arbitratorid'])
                    }}
                  />
                )
              }
            </Item>
          </Cell>
          {this.renderNormal(data)}
        </Line>
      </div>
    )
  }
}

SecretaryGeneralInput.proptypes = {
  caseDetail: PropTypes.object,
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  formRef: PropTypes.object
}

SecretaryGeneralInput.defaultProps = {
  caseDetail: {},
  userInfo: {},
  instance: {},
  formRef: {}
}
